package services

import (
	"book-management-system/models"
	"book-management-system/repositories"
	"errors"
	"gorm.io/gorm"
)

func BorrowBook(userID, bookID string) error {
	return repositories.DB.Transaction(func(tx *gorm.DB) error {
		book, err := repositories.GetBookByID(tx, bookID)
		if err != nil {
			return err
		}

		if book.Quantity <= 0 {
			return errors.New("book out of stock")
		}

		book.Quantity--
		if err := repositories.UpdateBook(tx, book); err != nil {
			return err
		}

		if err := repositories.CreateBorrowRecord(tx, userID, bookID); err != nil {
			return err
		}

		return nil
	})
}

func ReturnBook(userID, bookID string) error {
	return repositories.DB.Transaction(func(tx *gorm.DB) error {
		record, err := repositories.GetBorrowRecord(tx, userID, bookID)
		if err != nil {
			return err
		}

		if err := repositories.MarkAsReturned(tx, record); err != nil {
			return err
		}

		book, err := repositories.GetBookByID(tx, bookID)
		if err != nil {
			return err
		}

		book.Quantity++
		return repositories.UpdateBook(tx, book)
	})
}

func GetUserBorrowedBooks(userID string) ([]models.Book, error) {
	return repositories.GetBooksBorrowedByUser(userID)
}
